---
title: Custom classifier
description: How to configure and customize the Classifier in the Agent Squad System
---

This guide explains how to create a custom classifier for the Agent Squad by extending the abstract `Classifier` class. Custom classifiers allow you to implement your own logic for intent classification and agent selection.

## Overview

To create a custom classifier, you need to:

1. Extend the abstract `Classifier` class
2. Implement the required `process_request` method
3. Optionally override other methods for additional customization

## Step-by-Step Guide

### 1. Extend the Classifier Class

Create a new class that extends the abstract `Classifier` class:

import { Tabs, TabItem } from '@astrojs/starlight/components';

<Tabs syncKey="runtime">
  <TabItem label="TypeScript" icon="seti:typescript" color="blue">
    ```typescript
    import { Classifier } from './path-to-classifier';
    import { ClassifierResult, ConversationMessage } from './path-to-types';

    export class MyCustomClassifier extends Classifier {
      // Implementation will go here
    }
    ```
  </TabItem>
  <TabItem label="Python" icon="seti:python">
    ```python
    from agent_squad.classifiers import Classifier
    from agent_squad.types import ClassifierResult, ConversationMessage
    from typing import List

    class MyCustomClassifier(Classifier):
        # Implementation will go here
        pass
    ```
  </TabItem>
</Tabs>

### 2. Implement the process_request Method

The `process_request` method is the core of your custom classifier. It should analyze the input and return a `ClassifierResult`:

<Tabs syncKey="runtime">
  <TabItem label="TypeScript" icon="seti:typescript" color="blue">
    ```typescript
    export class MyCustomClassifier extends Classifier {
      async processRequest(
        inputText: string,
        chatHistory: ConversationMessage[]
      ): Promise<ClassifierResult> {
        // Your custom classification logic goes here

        return {
          selectedAgent: firstAgent,
          confidence: 1.0
        };
      }
    }
    ```
  </TabItem>
  <TabItem label="Python" icon="seti:python">
    ```python
    class MyCustomClassifier(Classifier):
        async def process_request(
            self,
            input_text: str,
            chat_history: List[ConversationMessage]
        ) -> ClassifierResult:
            # Your custom classification logic goes here

            first_agent = next(iter(self.agents.values()))
            return ClassifierResult(
                selected_agent=first_agent,
                confidence=1.0
            )
    ```
  </TabItem>
</Tabs>

## Using Your Custom Classifier

To use your custom classifier with the Agent Squad:

<Tabs syncKey="runtime">
  <TabItem label="TypeScript" icon="seti:typescript" color="blue">
    ```typescript
    import { AgentSquad } from './path-to-agent-squad';
    import { MyCustomClassifier } from './path-to-my-custom-classifier';

    const customClassifier = new MyCustomClassifier();
    const orchestrator = new AgentSquad({ classifier: customClassifier });
    ```
  </TabItem>
  <TabItem label="Python" icon="seti:python">
    ```python
    from agent_squad.orchestrator import AgentSquad
    from path_to_my_custom_classifier import MyCustomClassifier

    custom_classifier = MyCustomClassifier()
    orchestrator = AgentSquad(classifier=custom_classifier)
    ```
  </TabItem>
</Tabs>

## Best Practices

1. **Robust Analysis**: Implement thorough analysis of the input text and chat history to make informed classification decisions.
2. **Error Handling**: Include proper error handling in your `process_request` method to gracefully handle unexpected inputs or processing errors.
3. **Extensibility**: Design your custom classifier to be easily extensible for future improvements or adaptations.
4. **Performance**: Consider the performance implications of your classification logic, especially for high-volume applications.

## Example: Keyword-Based Classifier

Here's an example of a simple keyword-based classifier:

<Tabs syncKey="runtime">
  <TabItem label="TypeScript" icon="seti:typescript" color="blue">
    ```typescript
    import { Classifier } from './path-to-classifier';
    import { ClassifierResult, ConversationMessage, Agent } from './path-to-types';

    export class KeywordClassifier extends Classifier {
      private keywordMap: { [keyword: string]: string };

      constructor(keywordMap: { [keyword: string]: string }) {
        super();
        this.keywordMap = keywordMap;
      }

      async processRequest(
        inputText: string,
        chatHistory: ConversationMessage[]
      ): Promise<ClassifierResult> {
        const lowercaseInput = inputText.toLowerCase();

        for (const [keyword, agentId] of Object.entries(this.keywordMap)) {
          if (lowercaseInput.includes(keyword)) {
            const selectedAgent = this.getAgentById(agentId);
            return {
              selectedAgent,
              confidence: 0.8 // Simple fixed confidence
            };
          }
        }

        // Default to the first agent if no keyword matches
        const defaultAgent = Object.values(this.agents)[0];
        return {
          selectedAgent: defaultAgent,
          confidence: 0.5
        };
      }
    }

    // Usage
    const keywordMap = {
      'technical': 'tech-support-agent',
      'billing': 'billing-agent',
      'sales': 'sales-agent'
    };
    const keywordClassifier = new KeywordClassifier(keywordMap);
    const orchestrator = new AgentSquad({ classifier: keywordClassifier });
    ```
  </TabItem>
  <TabItem label="Python" icon="seti:python">
    ```python
    from agent_squad.classifiers import Classifier
    from agent_squad.types import ClassifierResult, ConversationMessage
    from agent_squad.orchestrator import AgentSquad
    from typing import List, Dict

    class KeywordClassifier(Classifier):
        def __init__(self, keyword_map: Dict[str, str]):
            super().__init__()
            self.keyword_map = keyword_map

        async def process_request(
            self,
            input_text: str,
            chat_history: List[ConversationMessage]
        ) -> ClassifierResult:
            lowercase_input = input_text.lower()

            for keyword, agent_id in self.keyword_map.items():
                if keyword in lowercase_input:
                    selected_agent = self.get_agent_by_id(agent_id)
                    return ClassifierResult(
                        selected_agent=selected_agent,
                        confidence=0.8  # Simple fixed confidence
                    )

            # Default to the first agent if no keyword matches
            default_agent = next(iter(self.agents.values()))
            return ClassifierResult(
                selected_agent=default_agent,
                confidence=0.5
            )

    # Usage
    keyword_map = {
        'technical': 'tech-support-agent',
        'billing': 'billing-agent',
        'sales': 'sales-agent'
    }
    keyword_classifier = KeywordClassifier(keyword_map)
    orchestrator = AgentSquad(classifier=keyword_classifier)
    ```
  </TabItem>
</Tabs>

This example demonstrates a basic keyword-based classification strategy. You can expand on this concept to create more sophisticated custom classifiers based on your specific needs.

## Conclusion

Creating a custom classifier allows you to implement specialized logic for intent classification and agent selection in the Agent Squad. By extending the `Classifier` class and implementing the `process_request` method, you can tailor the classification process to your specific use case and requirements.

Remember to thoroughly test your custom classifier to ensure it performs well across a wide range of inputs and scenarios.